package com.dev.sqlite.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dev.sqlite.entity.User;
import com.dev.sqlite.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2021-03-09
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public ResponseEntity<List<User>> list() {
        return ResponseEntity.ok(userService.list());
    }

    @GetMapping("/page")
    public ResponseEntity<Page> list(Page page) {
        return ResponseEntity.ok(userService.page(page));
    }

    @GetMapping("/getOne/{id}")
    public ResponseEntity<User> getOne(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(userService.getById(id));
    }

    @PostMapping("/insert")
    public ResponseEntity<Boolean> insert(@RequestBody User user) {
        return ResponseEntity.ok(userService.save(user));
    }

    @PostMapping("/insertBatch")
    public ResponseEntity<Object> insert(@RequestBody List<User> datas) {
        if (CollectionUtils.isEmpty(datas)){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("参数为空!");
        }
        int start = 0;
        int end = 500;
        if (datas.size() > end){
            while (datas.size() > start){
                List<User> users2;
                if (datas.size() < end){
                    users2 = datas.subList(start, datas.size());
                    userService.saveBatch(users2, users2.size());
                }else {
                    users2 = datas.subList(start, end);
                    userService.saveBatch(users2, end);
                }
                datas.removeAll(users2);
            }
        }else {
            userService.saveBatch(datas, datas.size());
        }
        return ResponseEntity.ok("操作成功!");
    }

    @PutMapping("/update")
    public ResponseEntity<Boolean> update(@RequestBody User user) {
        return ResponseEntity.ok(userService.updateById(user));
    }

    @DeleteMapping("/remove/{id}")
    public ResponseEntity<Boolean> remove(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(userService.removeById(id));
    }
}